package com.example.administrator.ardemo.utils.permission;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限工具类
 */
public class PermissionUtils {
    private OnPermissionSuccessCallback mPermissionSuccessAcion;
    private String mPermissionDescription;
    private List<String> needPermissions = new ArrayList<>(); // 未获得的权限列表
    private static final int MY_PERMISSIONS_REQUEST = 1001;
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    private static final int REQUEST_CODE_REQUEST_SETTING = 1027;

    /**
     * 请求权限
     *
     * @param permissions               权限列表
     * @param action                    获得权限成功之后的回调
     * @param needPermissionDescription 需要这些权限的原因（当用户第一次拒绝之后，会提示这个原因）
     */
    public void requestPermission(final Activity activity, String[] permissions, OnPermissionSuccessCallback action, String needPermissionDescription) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                needPermissions.add(permission);
            }
        }
        if (needPermissions == null || needPermissions.size() <= 0) {  // 已经获得权限，直接执行
            action.call();
            return;
        }
        boolean needRationale = false; // 是否需要权限的原因。当申请的权限被用户拒绝之后，再次申请时会提示
        for (String p : needPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, p)) {
                needRationale = true;
                break;
            }
        }

        mPermissionSuccessAcion = action;  // 获得权限之后的回调
        mPermissionDescription = needPermissionDescription;  // 申请权限的描述信息

        if (needRationale) { // 提示之后再申请权限
            new AlertDialog.Builder(activity)
                    .setTitle("权限申请")
                    .setMessage(needPermissionDescription)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(activity,
                                    needPermissions.toArray(new String[0]),
                                    MY_PERMISSIONS_REQUEST);
                            dialog.dismiss();
                        }
                    }).show();
        } else { // 直接申请权限
            ActivityCompat.requestPermissions(activity,
                    needPermissions.toArray(new String[0]),
                    MY_PERMISSIONS_REQUEST);
        }
    }

    /**
     * 请求权限的回调处理方法
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public void onRequestPermissionsResult(final Activity activity, int requestCode, String[] permissions, int[]
            grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                }
            }
            if (allGranted) {  // 已获得全部权限
                if (mPermissionSuccessAcion != null)
                    mPermissionSuccessAcion.call();
            } else {  // 未获得权限，提示是否打开设置页面
                if (!TextUtils.isEmpty(mPermissionDescription)) {
                    new AlertDialog.Builder(activity)
                            .setTitle("权限申请失败")
                            .setMessage(mPermissionDescription + "\n是否前往设置？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startAppSettings(activity);
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            activity.finish();
                        }
                    }).show();
                }

            }
            return;
        }
    }

    /**
     * 跳转到app的设置页面去设置权限
     */
    private void startAppSettings(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + activity.getPackageName()));
        activity.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING);
    }

    /**
     * 去设置里面手动开启权限后仍然要持续检查是否已经开启所有权限
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data, OnPermissionFailureCallback mPermissionFailureAcion) {
        if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
            List<String> list = new ArrayList<>();
            for (String permission : needPermissions) {
                if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_DENIED) {
                    list.add(permission);
                }
            }
            if (list.size() > 0) {
                mPermissionFailureAcion.call(list.toArray(new String[list.size()]));
            } else {
                if (mPermissionSuccessAcion != null)
                    mPermissionSuccessAcion.call();
            }
        }
    }
}
